<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-combo-box.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">
<link rel="import" href="redux-mixin.html">

<dom-module id="view-setup-station">
    <template>
        <style include="shared-styles app-grid-style flat-button">
            :host {
                display: block;
                margin: 10px;
                --app-grid-item-height: 50%;
            }

            .btn {
                margin: 15px 10px 0 0;
                width: 250px;
            }

            .station {
                margin: 10px;
                padding: 20px;
                border: 1px solid rgba(0, 0, 0, .10);
                border-radius: 5px;
            }

            .station p {
                margin: 10px 0;
            }

            .station h1 {
                text-align: center;
            }

            .station-info-group {
                margin-bottom: auto;
            }

            .flex-container {
                padding: 10px;
                margin: 0;
                list-style: none;
                -ms-box-orient: horizontal;
                display: -webkit-box;
                display: -moz-box;
                display: -ms-flexbox;
                display: -moz-flex;
                display: -webkit-flex;
                display: flex;
                align-items: center;
                justify-content: flex-start;
            }

            .flex-item {
                background: #202020;
                width: 200px;
                height: 75px;
                margin: 10px;
                line-height: 75px;
                color: white;
                font-size: 1.25em;
                text-align: center;
                flex: 1;
                border-radius: 5px;
            }

            .machine-item {
                cursor: pointer;
            }

            .machine-counter {
                margin: 10px 0 0 0;
            }

            .machine-list {
                height: 300px;
            }

            .btn-block {
                width: 100%;
            }

            .add-btn {
                margin: 20px 0;
                width: 250px;
            }
        </style>
        <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
        <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
        <firebase-query app-name="smart-mes" id="stationQuery" path="/data/[[k.key]]/factoryData/station" data="{{stationItems}}"
            order-by-child="st_number"></firebase-query>
        <firebase-query app-name="smart-mes" id="machineQuery" path="/data/[[k.key]]/factoryData/machine" data="{{machineItems}}"
            order-by-child="name"></firebase-query>
        <firebase-document app-name="smart-mes" id="editStationQuery" path="/data/[[k.key]]/factoryData/station/[[editKey]]" data="{{editStationItems}}"></firebase-document>
        <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
        <!-- Add Station Card -->
        <div class="card main-card" hidden="[[showAddStation]]">
            <h1 class="title">{{localize('add-station')}}</h1>
            <paper-input type="number" id="stationNumber" name="station-number" label="{{localize('station-number')}}" value="[[getStationNumber(stationItems.length)]]"
                min="1" max="999" readonly required always-float-label></paper-input>
            <paper-input type="text" id="stationName" name="station-name" label="{{localize('station-name')}}" required error-message="Invalid Input"
                always-float-label></paper-input>
            <vaadin-combo-box label="Machine" id="machineSelector" items="[[machineItems]]" name="stationName" item-label-path="name"
                item-value-path="name" loading="[[!machineItems]]" required always-float-label>
                <template>
                    <paper-item>
                        <paper-item-body two-line style="min-height: 0">
                            <div readonly>[[item.name]]</div>
                            <div secondary>Type [[item.type]] / No. [[item.number]]</div>
                        </paper-item-body>
                    </paper-item>
                </template>
            </vaadin-combo-box>
            <p class="machine-counter">You added [[stationMachineCount]] / [[stationMaxMachine]] {{localize('machine')}}</p>
            <flat-button class="add-btn" on-click="addMachine">
                <button>{{localize('add-machine')}}</button>
            </flat-button>
            <div class="frame">
                <ul class="flex-container wrap">
                    <template is="dom-repeat" items="{{machines}}" as="machineItem">
                        <li class="flex-item machine-item" on-click="removeMachine" number="[[index]]" title="Click here to remove this item">[[machineItem.name]]
                        </li>
                    </template>
                </ul>
            </div>
            <div class="center">
                <flat-button class="btn" on-click="openStationMainCard">
                    <button>{{localize('dismiss')}}</button>
                </flat-button>
                <flat-button class="btn shamrock" on-click="addStation">
                    <button>{{localize('add')}}</button>
                </flat-button>
            </div>
        </div>
        <!-- Edit Station Card -->
        <div class="card main-card" hidden="[[showEditStation]]">
            <h1 class="title">{{localize('edit-station')}}</h1>
            <paper-input type="number" id="edit_stationNumber" name="station number" label="{{localize('station-number')}}" value="{{editStationItems.st_number}}"
                min="1" max="999" readonly required always-float-label></paper-input>
            <paper-input type="text" id="edit_stationName" name="station name" label="{{localize('station-name')}}" value="[[editStationItems.st_name]]"
                required error-message="Invalid Input" always-float-label></paper-input>
            <vaadin-combo-box label="Machine" id="edit_machineSelector" items="[[machineItems]]" name="machine station" item-label-path="name"
                item-value-path="name" loading="[[!machineItems]]" required always-float-label>
                <template>
                    <paper-item>
                        <paper-item-body>
                            <div readonly>[[item.name]]</div>
                        </paper-item-body>
                    </paper-item>
                </template>
            </vaadin-combo-box>
            <p class="machine-counter">You added [[stationEditMachineCount]] / [[stationMaxMachine]] {{localize('machine')}}</p>
            <flat-button class="add-btn" on-click="editAddMachine">
                <button>{{localize('add-machine')}}</button>
            </flat-button>
            <div class="frame">
                <ul class="flex-container wrap">
                    <template is="dom-repeat" items="{{editMachines}}" as="machineItem">
                        <li class="flex-item machine-item" on-click="editRemoveMachine" number="[[index]]" title="Click here to remove this item">[[machineItem.name]]
                        </li>
                    </template>
                </ul>
            </div>
            <div class="center">
                <flat-button class="btn" on-click="dismissEditStation">
                    <button>{{localize('dismiss')}}</button>
                </flat-button>
                <flat-button class="btn shamrock" on-click="saveStation">
                    <button>{{localize('save')}}</button>
                </flat-button>
            </div>
        </div>
        <!-- Station Manangement -->
        <div class="card main-card" hidden="[[showListStation]]">
            <h1 class="title">{{localize('station-management')}}</h1>
            <h1 class="sub-title center" hidden="[[machineItems]]">{{localize('please-add-machine-before-adding-station')}}</h1>
            <ul class="app-grid">
                <template is="dom-repeat" index-as="number" items="{{stationItems}}"
                    as="stationItem">
                    <li>
                        <div class="station">
                            <div class="station-info-group">
                                <h2 class="title">[[stationItem.st_name]]</h2>
                                <p>{{localize('station-number')}}: [[stationItem.st_number]]</p>
                                <p>{{localize('station-machine')}}: [[stationItem.st_machine.length]] / [[stationMaxMachine]]</p>
                                <div class="frame">
                                    <div class="machine-list">
                                        <iron-list items="[[stationItem.st_machine]]" as="machineItem">
                                            <template>
                                                <div tabindex$="[[tabIndex]]" class="item">
                                                    <p class="bold">[[machineItem.name]]</p>
                                                    <p>{{localize('type')}}: [[machineItem.code]]</p>
                                                </div>
                                            </template>
                                        </iron-list>
                                    </div>
                                </div>
                            </div>
                            <flat-button class="btn btn-block" on-click="openEditStationCard" station="[[stationItem]]">
                                <button>{{localize('edit')}}</button>
                            </flat-button>
                            <flat-button class="btn btn-block thunderbird" on-click="removeStation" station="[[stationItem]]">
                                <button>{{localize('remove')}}</button>
                            </flat-button>
                        </div>
                    </li>
                </template>
            </ul>
            <div class="center">
                <paper-button class="btn" on-click="openAddStationCard">{{localize('add-station')}}</paper-button>
            </div>
        </div>
        <paper-toast id="toastAlert" always-on-top horizontal-align="right">{{localize(toastText)}}</paper-toast>
    </template>
    <script>
        /**
         * @ViewSetupStation
         * @polymer 
         * @extends {Polymer.Element}
         */
        class ViewSetupStation extends ReduxMixin(Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior], Polymer.Element)) {
            static get is() {
                return 'view-setup-station'
            }

            static get properties() {
                return {
                    language: String,
                    editKey: String,
                    toastText: String,
                    stationItems: {
                        type: Object,
                        notify: true
                    },
                    machineItems: Object,
                    editStationItems: Object,
                    stationMaxMachine: {
                        type: Number,
                        value: 20
                    },
                    showAddStation: {
                        type: Boolean,
                        value: true
                    },
                    showEditStation: {
                        type: Boolean,
                        value: true
                    },
                    showListStation: {
                        type: Boolean,
                        value: false
                    },
                    machines: {
                        type: Array,
                        statePath: 'machines',
                    },
                    editMachines: {
                        type: Array,
                        statePath: 'editMachines'
                    },
                    stationMachineCount: {
                        type: Number,
                        computed: 'computeMachineCount(machines)',
                        readOnly: true
                    },
                    stationEditMachineCount: {
                        type: Number,
                        computed: 'computeMachineCount(editMachines)',
                        readOnly: true
                    }
                }
            }

            static get actions() {
                return {
                    add(data) {
                        return {
                            type: 'ADD_MACHINE',
                            machines: data
                        }
                    },
                    remove(data) {
                        return {
                            type: 'REMOVE_MACHINE',
                            index: data
                        }
                    },
                    editCreate(data) {
                        return {
                            type: 'EDIT_SET_MACHINE',
                            editMachines: data
                        }
                    },
                    editAdd(data) {
                        return {
                            type: 'EDIT_ADD_MACHINE',
                            editMachines: data
                        }
                    },
                    editRemove(data) {
                        return {
                            type: 'EDIT_REMOVE_MACHINE',
                            index: data
                        }
                    },
                    clear() {
                        return {
                            type: 'CLEAR_MACHINE'
                        }
                    }
                }
            }

            static get observers() {
                return [
                    'setEditStationMachine(editStationItems.st_machine)'
                ]
            }
            
            getStationNumber(length) {
                if (length > 0) {
                    return length + 1
                } else {
                    return 1
                }
            }

            computeMachineCount(m) {
                if (m) {
                    return m.length
                } else {
                    return 0
                }
            }

            connectedCallback() {
                super.connectedCallback()
                this.loadResources(this.resolveUrl('../../data/locales.json'))
                const state = this.getState()
                //console.info("Redux state: ", state)
            }

            setEditStationMachine(m) {
                this.dispatch('editCreate', m)
            }

            addMachine() {
                let selector = this.$.machineSelector
                if (selector.value) {
                    // if found duplicate it will return index > -1
                    let isDuplicated = this.machines.map(item => item.number).indexOf(selector.selectedItem.number) > -1
                    if (this.machines.length < this.stationMaxMachine) {
                        if (isDuplicated) {
                            this.toastText = 'notification-already-added-this-machine'
                            this.$.toastAlert.open()
                            return
                        }
                        this.dispatch('add', selector.selectedItem)
                        selector.value = null
                        selector.focus()
                    } else {
                        window.alert(`Can't add more than ${this.stationMaxMachine} machines per station`)
                    }
                } else {
                    this.toastText = 'notification-please-select-machine-to-add'
                    this.$.toastAlert.open()
                }
            }

            removeMachine(e) {
                if (this.machines.length > 0) {
                    if (window.confirm("Delete this machines ?") == true) {
                        this.dispatch('remove', e.currentTarget.number);
                    }
                }
            }

            editAddMachine() {
                let selector = this.$.edit_machineSelector
                if (selector.value) {
                    // if found duplicate it will return index > -1
                    if (!this.editMachines) {
                        this.editMachines = []
                    }
                    let isDuplicated = this.editMachines.map(item => item.number).indexOf(selector.selectedItem
                        .number) > -1

                    if (this.editMachines.length < this.stationMaxMachine) {
                        if (isDuplicated) {
                            this.toastText = 'notification-already-added-this-machine'
                            this.$.toastAlert.open()
                            return
                        }
                        this.dispatch('editAdd', selector.selectedItem)
                        selector.value = null
                        selector.focus()
                    } else {
                        window.alert(`Can't add more than ${this.stationMaxMachine} machines per station`)
                    }
                } else {
                    this.toastText = 'notification-please-select-machine-to-add'
                    this.$.toastAlert.open()
                }
            }

            editRemoveMachine(e) {
                if (this.editMachines.length > 0) {
                    if (window.confirm("Delete this machines ?") == true) {
                        this.dispatch('editRemove', e.currentTarget.number);
                    }
                }
            }

            addStation() {
                const sname = this.$.stationName.value
                const snumber = this.$.stationNumber.value
                const smachine = this.machines
                const timestamp = Math.round(Date.now() / 1000.0)
                if (sname && snumber && smachine.length > 0) {
                    this.$.stationQuery.ref.push({
                        st_name: sname,
                        st_number: snumber,
                        st_machine: smachine,
                        st_install: timestamp
                    });
                    this.clearField()
                    this.dispatch('clear')
                    this.machines = []
                    this.toastText = 'notification-add-station-successfully'
                    this.$.toastAlert.open()
                    this.openStationMainCard()
                } else {
                    this.toastText = 'notification-empty-add-station'
                    this.$.toastAlert.open()
                }
            }

            removeStation(e) {
                if (window.confirm("Delete this station ?") == true) {
                    const key = e.currentTarget.station.$key
                    this.$.stationQuery.ref.child(key).remove()
                    this.toastText = 'notification-delete-station-successfully'
                    this.$.toastAlert.open()
                }
            }

            saveStation(e) {
                const sname = this.$.edit_stationName.value;
                const smachine = this.editMachines
                if (sname && smachine.length >= 0) {
                    this.$.editStationQuery.ref.update({
                        st_name: sname,
                        st_machine: smachine
                    });
                    this.toastText = 'notification-save-station-successfully'
                    this.$.toastAlert.open()
                    this.openStationMainCard()
                } else {
                    this.toastText = 'notification-empty-add-station'
                    this.$.toastAlert.open()
                }
            }

            clearField() {
                this.$.stationNumber.value = this.stationItems.length + 1;
                this.$.stationName.value = ""
                this.$.machineSelector.value = ""
                if (this.machines) {
                    this.dispatch('clear')
                    this.machines = []
                }
                this.editKey = ""
            }

            openAddStationCard() {
                this.showAddStation = false
                this.showListStation = true
            }

            openEditStationCard(e) {
                this.showEditStation = false
                this.showListStation = true
                const key = e.currentTarget.station.$key
                this.editKey = key
            }

            openStationMainCard() {
                this.showEditStation = true
                this.showAddStation = true
                this.showListStation = false
                this.clearField()
            }

            dismissEditStation() {
                this.showEditStation = true
                this.showAddStation = true
                this.showListStation = false
                this.clearField()
            }
        }
        customElements.define(ViewSetupStation.is, ViewSetupStation)
    </script>
</dom-module>